package project.server;

import project.common.Request;
import project.common.Response;
import project.common.User;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author oldliu
 * @since 1.0
 */
public class MainServer {
    public static void main(String[] args) throws IOException {
        ServerSocket st = new ServerSocket(9999);
        ExecutorService executors = Executors.newFixedThreadPool(20);
        System.out.println("服务器启动！");
        while (true) {
            //线程池。。。
            executors.submit(new ServerThread(st.accept()));
            //executors.submit(new MyOut(st.accept()));
        }
    }
}

class ServerThread implements Runnable {
    private final Socket s;

    //private List<User> users=new ArrayList<>();

    public ServerThread(Socket s) {
        this.s = s;

    }

    private List<User> getUsers() {
        try {
            XMLDecoder s = new XMLDecoder(new FileInputStream("users.xml"));
            Object o = s.readObject();
            return (List<User>) o;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    private void saveUsers(List<User> users) {
        try {
            XMLEncoder xd = new XMLEncoder(new FileOutputStream("users.xml"));
            xd.writeObject(users);
            xd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Response login(Request request) {
        Response resp = new Response();
        String name = (String) request.get("userName");//getKey
        String pass = (String) request.get("userPass");

        List<User> users = getUsers();
        for (User u : users) {
            if (u.getUserName().equals(name) && u.getUserPass().equals(pass)) {
                resp.setSuccess(true);
                return resp;
            }
        }

//        if ("admin".equals(name) && "123456".equals(pass)) {
//            resp.setSuccess(true);
//        } else {
//            resp.setSuccess(false);
//            resp.setMsg("错误的用户名或者密码！");
//        }
        resp.setSuccess(false);
        resp.setMsg("错误的用户名或者密码！");
        return resp;
    }

    //注册
    public Response register(Request request) {

        User user = new User((String) request.get("name"), (String) request.get("pass"));
        System.out.println(user.getUserName() + ">>>>>>>>>" + user.getUserPass());
        List<User> users = getUsers();
        Response resp = new Response(true);
        users.add(user);
        saveUsers(users);

        return resp;
    }

    //发两个信息，文件名+内容字节数组
    public Response upload(Request request) {
        Response resp = new Response(true);
        String fileName = (String) request.get("fileName");
        byte[] contents = (byte[]) request.get("content");
        try {
            //同名文件覆盖的问题
            FileOutputStream fout = new FileOutputStream(new File("D:\\Documents\\桌面\\temp", System.currentTimeMillis() + fileName));
            fout.write(contents);
            fout.close();
            System.out.println("从" + s + "收到了文件" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setSuccess(false);
            resp.setMsg(e.toString());
        }

        return resp;
    }

    @Override
    public void run() {
        System.out.println(s + "连接了。。。");
        ObjectInputStream oin = null;
        ObjectOutputStream oout = null;

        try {
            InputStream in = s.getInputStream();
            //System.out.println("真正的类型是："+in.getClass().getName());
            OutputStream out = s.getOutputStream();
            //用对象
            oin = new ObjectInputStream(in);
            oout = new ObjectOutputStream(out);
            Response resp = new Response();
            while (true) {
                Request request = (Request) oin.readObject();
                Method mt = this.getClass().getDeclaredMethod(request.getAction(), Request.class);
                resp = (Response) mt.invoke(this, request);
//                if (request.getAction().equals(Constants.LOGIN)) {
//                    resp = login(request);
////                    String name=(String)request.get("userName");//getKey
////                    String pass=(String)request.get("userPass");
////                    if("admin".equals(name)&&"123456".equals(pass)){
////                        resp.setSuccess(true);
////                    }else
////                    {
////                        resp.setSuccess(false);
////                        resp.setMsg("错误的用户名或者密码！");
////                    }
//                } else if (request.getAction().equals("register")) {
//                    resp = register(request);
//                } else if (request.getAction().equals("upload")) {
//                    resp = upload(request);
//                } else {
//                    resp.setSuccess(false);
//                    resp.setMsg("未知功能！");
//                }
                oout.writeObject(resp);
                oout.reset();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (s.isConnected()) {
                Response resp2 = new Response(false, "出现异常：" + e);
                try {
                    oout.writeObject(resp2);
                    oout.reset();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } finally {
            try {
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}


class MyOut implements Runnable {
    private final Socket s;

    public MyOut(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            InputStream in = s.getInputStream();
            OutputStream out = s.getOutputStream();
            System.setOut(new PrintStream(out, true));
            //System.setIn(in);
            Scanner sc = new Scanner(in);
            while (true) {
                System.out.println("请你输入你的名字：");
                //System.out.flush();
                String yourname = sc.next();
                System.out.println("请你输入你的密码：");
                //System.out.flush();
                String yourpass = sc.next();
                System.out.println("请你输入你的年龄：");
                //System.out.flush();
                int age = sc.nextInt();
                // System.out.println("你叫"+yourname+",密码是"+yourpass+",年龄是"+age);
                //System.out.flush();
//                System.out.println();
//                System.out.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (Exception e) {

            }
        }
    }
}